package form

import (
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/service"
	"yak.admin/src/util"
)

type ReportCheckForm struct {
	Id       int `form:"id" validate:"required" chn:"ID"`
	Province string
	City     string
	County   string
	IsSuper  bool
	Comment  string `form:"comment" validate:"max=128" chn:"评估意见"`
	Status   int
	AdminId int
}

func (search *ReportCheckForm) Drug() bool {
	db := util.GetMysqlPool().Handler()
	report := entity.DrugReport{}
	var condition map[string]interface{}
	if search.IsSuper {
		condition = map[string]interface{}{"id": search.Id, "status": util.PendingStatus}
	} else {
		condition = map[string]interface{}{"id": search.Id, "status": util.PendingStatus, "province": search.Province, "city": search.City, "county": search.County}
	}

	if !db.Where(condition).First(&report).RecordNotFound() {
		if db.Model(&report).Updates(map[string]interface{}{
			"comment": search.Comment, "status": search.Status, "checked_at": time.Now().Unix(), "admin_id": search.AdminId,
		}).RowsAffected > 0 {
			behavior := service.BehaviorService{}
			if search.Status == util.IgnoreStatus {
				behavior.UnwatchDrug(report.Province, report.City, report.County)
			}
			if search.Status == util.FollowStatus {
				behavior.WatchDrug(report.Province, report.City, report.County)
			}

			messageService := service.MessageService{UserId:report.UserId}
			str := time.Unix(report.ReportedAt, 0).Format("2006-01-02 15:04:05")
			if report.Status == 2 {
				if messageService.SetDrugMessage(str) == nil {
					behavior.WriteMessageTimes(report.UserId)
				}
			}

			return true
		}
	}
	return false
}

func (search *ReportCheckForm) Device() bool {
	db := util.GetMysqlPool().Handler()
	report := entity.DeviceReport{}
	var condition map[string]interface{}
	if search.IsSuper {
		condition = map[string]interface{}{"id": search.Id, "status": util.PendingStatus}
	} else {
		condition = map[string]interface{}{"id": search.Id, "status": util.PendingStatus, "province": search.Province, "city": search.City, "county": search.County}
	}

	if !db.Where(condition).First(&report).RecordNotFound() {
		if db.Model(&report).Updates(map[string]interface{}{
			"comment": search.Comment, "status": search.Status, "checked_at": time.Now().Unix(), "admin_id": search.AdminId,
		}).RowsAffected > 0 {
			behavior := service.BehaviorService{}
			if search.Status == util.IgnoreStatus {
				behavior.UnwatchDevice(report.Province, report.City, report.County)
			}
			if search.Status == util.FollowStatus {
				behavior.WatchDevice(report.Province, report.City, report.County)
			}

			messageService := service.MessageService{UserId:report.UserId}
			str := time.Unix(report.ReportedAt, 0).Format("2006-01-02 15:04:05")
			if report.Status == 2 {
				if messageService.SetDeviceMessage(str) == nil {
					behavior.WriteMessageTimes(report.UserId)
				}
			}

			return true
		}
	}
	return false
}
